package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    /**
     * 员工分页查询
     *
     * @param param
     * @return
     */
    @Override
    public PageResult pageEmp(EmpQueryParam param) {
        //1.设置分页参数
//        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("Update_time"));

//        //2.构建查询条件
//        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(param.getName() != null && ObjectUtil.isNotEmpty(param.getName()), Emp::getName, param.getName())
//                .eq(param.getGender() != null, Emp::getGender, param.getGender())
//                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
//
//        //3.发起分页查询
//        Page<Emp> pageResult = this.page(page, queryWrapper);

        //2+3简化方式（主流） - 构建查询条件，再发起分页查询
        Page<Emp> pageResult = this.lambdaQuery().like(param.getName() != null && ObjectUtil.isNotEmpty(param.getName()), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);

        //4.为records数据设置部门名称
        List<Emp> records = pageResult.getRecords();
        records.forEach(e -> {
            //4.1根据id查询部门名称
            Dept dept = deptService.getById(e.getDeptId());
            if (ObjectUtil.isNotEmpty(dept)) {
                e.setDeptName(dept.getName());
            }
        });

        //5.返回分页结果
        return new PageResult(pageResult.getTotal(), records);
    }

    /**
     * 保存员工信息
     *
     * @param emp
     */
    @Transactional
    @Override
    public void saveEmp(Emp emp) {
        //1.保存员工基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);

        //2.保存员工经历信息
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(e -> {
            e.setEmpId(emp.getId());//mybatis-plus能自动进行逐渐回填
            empExprService.save(e);
        });
    }

    /**
     * 批量删除员工信息
     *
     * @param ids
     */
    @Transactional
    @Override
    public void removeEmp(List<Integer> ids) {
        //1.删除员工基本信息
        this.removeBatchByIds(ids);

        //2.删除员工经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));//LambdaQueryWrapper有. 记住要写泛型
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Emp queryById(Integer id) {
        //1.查询员工基本信息
        Emp emp = this.getById(id);

        //2.查询员工经历信息
        List<EmpExpr> empExprList = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id));

        //3.将员工经历信息设置到员工实体，返回结果
        emp.setExprList(empExprList);
        return emp;
    }

    /**
     * 修改员工信息
     *
     * @param emp
     */
    @Transactional
    @Override
    public void updateEmp(Emp emp) {
        //1.修改员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //2.删除员工经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //3.添加员工经历信息
        List<EmpExpr> exprList = emp.getExprList();
        if (ObjectUtil.isNotEmpty(exprList) && exprList != null) {
            exprList.forEach(e -> {
                e.setEmpId(emp.getId());
            });
        }
        empExprService.saveBatch(exprList);
    }
}
